<template>
  <el-container style="height: 500px; border: 1px solid #eee">
    <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
      <el-menu :default-openeds="['1', '3']">
        <el-submenu index="1">
          <template #title>
            <el-icon><Timer /></el-icon>
            <span>案件状态</span>
          </template>
          <el-menu-item-group>
            <template #title>进行中</template>
            <el-menu-item
              v-for="item in leftItem1"
              :key="item.caseId"
              :index="item.caseId"
              @click="queryByName(item)"
            >
              {{ item.caseName }}
            </el-menu-item>
          </el-menu-item-group>
          <el-menu-item-group>
            <template #title>已完结</template>
            <el-menu-item
              v-for="item in leftItem2"
              :key="item.caseId"
              :index="item.caseId"
              @click="queryByName(item)"
            >
              {{ item.caseName }}
            </el-menu-item>
          </el-menu-item-group>
        </el-submenu>

        <el-submenu index="2">
          <template #title>
            <el-icon><User /></el-icon>
            <span>律师</span>
          </template>
          <el-menu-item-group>
            <template #title>律师名称</template>
            <el-menu-item
              v-for="item in lawyerNames"
              :key="item.lawyerId"
              :index="item.lawyerId"
              @click="queryByName(item)"
            >
              {{ item.lawyerName }}
            </el-menu-item>
          </el-menu-item-group>
        </el-submenu>
      </el-menu>
    </el-aside>

    <el-container>
      <el-header style="text-align: right; font-size: 12px">
        <el-date-picker
          style="width: 150px; margin-right: 30px"
          type="month"
          placeholder="选择月"
          v-model="query.dateMonth"
          value-format="yyyy-MM"
        />

        <el-button
          type="primary"
          :icon="Search"
          @click="handleSearch"
        >
          搜索
        </el-button>

        <el-button
          type="primary"
          :icon="Plus"
          @click="addCase"
          style="margin-right: 600px"
        >
          录入案件
        </el-button>

        <span>案件详情</span>
      </el-header>

      <el-main>
        <el-table :data="tableData">
          <el-table-column prop="year" label="年份" width="80" />
          <el-table-column prop="contractNumber" label="案件编号" width="80" />
          <el-table-column prop="caseName" label="案件名称" />
          <el-table-column prop="caseType" label="案件类型" />
          <el-table-column prop="representationType" label="代理类型" />
          <el-table-column prop="court" label="开庭法院" width="150" />
          <el-table-column prop="courtDate" label="开庭年月" />
          <el-table-column prop="status" label="状态" />
          <el-table-column prop="result" label="结果" />
        </el-table>
      </el-main>

      <!-- 录入弹出框 -->
      <el-dialog
        title="录入新案件"
        v-model="addVisible"
        width="30%"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="案件编号" prop="caseId">
            <el-input v-model="form.caseId" />
          </el-form-item>

          <el-form-item label="案件名称" prop="caseName">
            <el-input v-model="form.caseName" />
          </el-form-item>

          <el-form-item label="案件类型" prop="caseType">
            <el-select v-model="form.caseType" placeholder="请选择">
              <el-option label="刑事案件" value="刑事案件" />
              <el-option label="民事案件" value="民事案件" />
              <el-option label="行政案件" value="行政案件" />
              <el-option label="经济案件" value="经济案件" />
            </el-select>
          </el-form-item>

          <el-form-item label="代理类型" prop="representationType">
            <el-select v-model="form.representationType" placeholder="请选择">
              <el-option label="原告" value="原告" />
              <el-option label="被告" value="被告" />
            </el-select>
          </el-form-item>

          <el-form-item label="开庭法院" prop="court">
            <el-input v-model="form.court" />
          </el-form-item>

          <el-form-item label="律师名称" prop="lawyerName">
            <el-input v-model="form.lawyerName" />
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择">
              <el-option label="进行中" value="进行中" />
              <el-option label="已结案" value="已结案" />
            </el-select>
          </el-form-item>

          <el-form-item label="开庭年月" prop="courtDate">
            <el-date-picker
              v-model="form.courtDate"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            />
          </el-form-item>

          <el-form-item label="结果" prop="result">
            <el-select v-model="form.result" placeholder="请选择">
              <el-option label="胜诉" value="胜诉" />
              <el-option label="败诉" value="败诉" />
              <el-option label="调节" value="调节" />
            </el-select>
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="addVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEdit">确定</el-button>
        </template>
      </el-dialog>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Timer, User, Search, Plus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'

// 导入API
import {
  getCaseWhereStatus1,
  getCaseWhereStatus2,
  getLawyers,
  selectCaseByConditon,
  addCases
} from '../../api/case'

// 类型定义
interface CaseItem {
  caseId: string
  caseName: string
  caseType?: string
  representationType?: string
  court?: string
  courtDate?: string
  status?: string
  result?: string
  lawyerName?: string
  year?: string
  contractNumber?: string
}

interface LawyerItem {
  lawyerId: string
  lawyerName: string
}

// 表单验证规则
const rules = reactive({
  caseName: [
    { required: true, message: '案件名称不能为空', trigger: 'blur' }
  ],
  caseType: [
    { required: true, message: '请选择案件类型', trigger: 'change' }
  ],
  representationType: [
    { required: true, message: '请选择代理类型', trigger: 'change' }
  ],
  court: [
    { required: true, message: '请输入开庭法院', trigger: 'blur' }
  ],
  lawyerName: [
    { required: true, message: '请输入律师名称', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  courtDate: [
    { required: true, message: '请选择开庭日期', trigger: 'change' }
  ],
  result: [
    { required: true, message: '请选择结果', trigger: 'change' }
  ]
})

// 响应式变量
const formRef = ref<FormInstance>()
const addVisible = ref(false)
const leftItem1 = ref<CaseItem[]>([])  // 进行中案件
const leftItem2 = ref<CaseItem[]>([])  // 已完结案件
const lawyerNames = ref<LawyerItem[]>([])  // 律师列表
const tableData = ref<CaseItem[]>([])  // 表格数据

// 查询参数
const query = reactive({
  dateMonth: '',
  lawyerName: '',
  caseName: '',
  pageIndex: 1
})

// 表单数据
const form = reactive<CaseItem>({
  caseId: '',
  caseName: '',
  caseType: '',
  representationType: '',
  court: '',
  lawyerName: '',
  status: '',
  courtDate: '',
  result: ''
})

// 页面加载时获取数据
onMounted(() => {
  getData()
})

// 获取所有数据
const getData = () => {
  // 获取表格数据
  selectCaseByConditon(query).then(res => {
    if (res.code === 200) {
      tableData.value = res.data
    } else {
      ElMessage.error('数据加载失败')
    }
  })

  // 获取进行中案件
  getCaseWhereStatus1().then(res => {
    if (res.code === 200) {
      leftItem1.value = res.data
    } else {
      ElMessage.error(res.msg || '获取进行中案件失败')
    }
  })

  // 获取已完结案件
  getCaseWhereStatus2().then(res => {
    if (res.code === 200) {
      leftItem2.value = res.data
    } else {
      ElMessage.error(res.msg || '获取已完结案件失败')
    }
  })

  // 获取律师列表
  getLawyers().then(res => {
    if (res.code === 200) {
      lawyerNames.value = res.data
    } else {
      ElMessage.error(res.msg || '获取律师列表失败')
    }
  })
}

// 搜索
const handleSearch = () => {
  query.pageIndex = 1
  getData()
}

// 打开新增弹窗
const addCase = () => {
  addVisible.value = true
  // 重置表单
  formRef.value?.resetFields()
  Object.keys(form).forEach(key => {
    form[key as keyof CaseItem] = ''
  })
}

// 保存新增案件
const saveEdit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const res = await addCases(form)
        if (res.code === 200) {
          ElMessage.success('添加成功')
          addVisible.value = false
          getData()
        } else {
          ElMessage.error('添加失败: ' + (res.msg || '未知错误'))
        }
      } catch (error) {
        ElMessage.error('添加失败，请重试')
      }
    } else {
      ElMessage.error('请输入正确的信息')
    }
  })
}

// 根据名称查询
const queryByName = (item: CaseItem | LawyerItem) => {
  // 重置查询参数
  const newQuery = { ...query }

  // 根据点击的是案件还是律师设置不同参数
  if ('caseName' in item) {
    newQuery.caseName = item.caseName
    newQuery.lawyerName = ''
  } else if ('lawyerName' in item) {
    newQuery.lawyerName = item.lawyerName
    newQuery.caseName = ''
  }

  // 执行查询
  selectCaseByConditon(newQuery).then(res => {
    if (res.code === 200) {
      tableData.value = res.data
    } else {
      ElMessage.error('查询失败')
    }
  })
}
</script>

<style scoped>
.handle-select {
  width: 120px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}

.el-header {
  background-color: rgba(205, 205, 205, 0.66);
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}

:deep(.el-card__body), .el-main {
  padding: 0px;
}
</style>
